import React, { useContext, useEffect, useState } from "react";
import classes from "./Cart.module.css";
import img from "../../../asset/bag.png";
import CartContext from "../../../store/cart";
import CartDetail from "./CartDetail/CartDetail";
import Checkout from "../../Checkout/Checkout";

function Cart() {
  const CartCxt = useContext(CartContext);

  // 购物车详情显示隐藏
  const [showCartDetail, setShowCartDetail] = useState(false);

  const showToggelCartDetail = () => {
    if (CartCxt.totalAmount === 0) {
      setShowCartDetail(false);
    } else {
      setShowCartDetail((pre) => !pre);
    }
  };

  /*
   * 在useEffect()可以传递第二个参数
   *     第二个参数是一个数组，在数组总可以指定Effect的依赖项
   *     指定后，只有当依赖项发生变化时，Effect才会被触发
   *     通常会将Effect中使用的所有的局部变量设置为依赖项
   *
   * */

  useEffect(() => {
    if (CartCxt.totalAmount === 0) {
      setShowCartDetail(false);
      setShowCheckout(false);
    }
  }, [CartCxt]);

  // 结账页面显示和隐藏
  const [showCheckout, setShowCheckout] = useState(false);
  const showToggelCheckout = () => {
    setShowCheckout(true);
  };
  const CloseCheckout = () => {
    setShowCheckout(false);
  };

  return (
    <div className={classes.Cart} onClick={showToggelCartDetail}>
      {/* 商品购物车 */}
      {showCartDetail && <CartDetail />}

      {/* 结账页面 */}
      {showCheckout && <Checkout onHide={CloseCheckout} />}

      <div className={classes.Icon}>
        <img src={img} alt="" />
        {CartCxt.totalAmount === 0 ? null : <span>{CartCxt.totalAmount}</span>}
      </div>

      {CartCxt.totalAmount === 0 ? (
        <div className={classes.NoMeal}>未选购商品</div>
      ) : (
        <div className={classes.TotalPrice}>{CartCxt.totalPrice}</div>
      )}

      <div className={classes.button}>
        <button
          onClick={showToggelCheckout}
          className={CartCxt.totalAmount === 0 ? classes.NoButton : ""}
        >
          去结算
        </button>
      </div>
    </div>
  );
}

export default Cart;
